require("./config/connect");
var msgModel = require('./models/msg');
console.log('worked');
var express = require('express'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http);
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname + '/www'));
app.use(bodyParser.urlencoded({
  extended: true
}));

// 房间用户名单
var roomInfo = {};
io.on('connection', function(socket){
  console.log('a user connected');
  var cid;
  var userName = '';
  //监听新用户加入
  socket.on('join', function(obj){
    console.log(obj);
    cid = obj.cid;
    userName = obj.username;
    // 将用户昵称加入房间名单中
    if (!roomInfo[cid]) {
      roomInfo[cid] = [userName];
    }else{
      roomInfo[cid].push(userName);
    }
    socket.join(cid);    // 加入房间
    // 通知房间内人员
    io.to(cid).emit('sys', userName + '加入了房间', roomInfo[cid]);
    console.log(userName + '加入了' + cid);
  });
  //监听用户发布聊天内容
  socket.on('message', function(obj){
    // 验证如果用户不在房间内则不给发送
    if (roomInfo[cid].indexOf(userName) === -1) {
      return false;
    }
    io.to(cid).emit('msg', userName, obj);
    // 插入数据库
    var date = new Date();
    var msg = {cid:cid,time:date,username:userName,content:obj};
    var newMsg = new msgModel(msg);
    newMsg.save(function(err, msg) {
      if (err) {
        console.log(err);
      }
    });
  });

  socket.on('leave', function () {
    socket.emit('disconnect');
  });

  //监听用户退出
  socket.on('disconnect', function(){
    // 从房间名单中移除
    console.log(roomInfo[cid]);

    var index = roomInfo[cid].indexOf(userName);
    console.log(index);
    if (index !== -1) {
      roomInfo[cid].splice(index, 1);
    }

    socket.leave(cid);    // 退出房间
    io.to(cid).emit('sys', userName + '退出了房间', roomInfo[cid]);
    console.log(userName + '退出了' + cid);
  });
});
http.listen(process.env.PORT || 3000);
// 显示所有聊天消息
app.post('/get-list',function(req,res){
  msgModel.findAll(req.body.cid,function (err, msgs) {
    if (err) {
      console.log(err);
    }
    res.json(msgs);
  });
});